package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.qcode.QCodeService;
import org.linlinjava.litemall.core.redis.RedisCache;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallShopSetting;
import org.linlinjava.litemall.db.service.LitemallShopBalanceService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.service.LitemallShopSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/admin/shop")
@Validated
public class AdminShopController {
    private final Log logger = LogFactory.getLog(AdminShopController.class);

    @Autowired
    private LitemallShopService shopService;
    @Autowired
    private LitemallShopSettingService shopSettingService;
    @Autowired
    private LitemallShopBalanceService shopBalanceService;
    @Autowired
    private QCodeService qCodeService;
    @Autowired
    private RedisCache redisCache;

    @RequiresPermissions("admin:shop:list")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String name, String shopPhone, String shopName,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
    	//LitemallAdmin admin = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
        List<LitemallShop> ShopList = shopService.querySelective(name, shopPhone, shopName, page, limit);
        return ResponseUtil.okList(ShopList);
    }

    private Object validate(LitemallShop shop) {
        String ShopName = shop.getShopName();
        if (StringUtils.isEmpty(ShopName)) {
            return ResponseUtil.badArgument();
        }
        String address = shop.getShopAddress();
        if (StringUtils.isEmpty(address)) {
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:shop:create")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody LitemallShop shop) {
        shopService.add(shop);
        return ResponseUtil.ok(shop);
    }


    @RequiresPermissions("admin:shop:update")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallShop shop) throws IOException {
        Object error = validate(shop);
        if (error != null) {
            return error;
        }
        //商家小程序码 如果没有，给他生成一个
        LitemallShop shopss = shopService.getOneByShopID(shop.getId());
        String shareUrl = shopss.getShareUrl();
        if(StringUtils.isEmpty(shareUrl)) {
        	//生成商家小程序码
        	shareUrl = qCodeService.createShopQcode(shop.getId());
        	shop.setShareUrl(shareUrl);
        }
        
        if (shopService.updateById(shop) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        //清除缓存
        deleteObject(shop.getId());
        return ResponseUtil.ok(shop);
    }
    
    @RequiresPermissions("admin:shop:updateShopBound")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店管理"}, button = "绑定APP管理")
    @PostMapping("/updateShopBound")
    public Object updateShopBound(@RequestBody LitemallShop shop) throws IOException {
        Object error = validate(shop);
        if (error != null) {
            return error;
        }
        if(shop.getAdminId()<1) {
        	return error;
        }
        //检查此id是否已有绑定店铺
        LitemallShop ss = shopService.getShopByAdminID(shop.getAdminId());
        if(ss!=null) {
        	return ResponseUtil.custom("此ID已绑定有商户！");
        }
        
        //商家小程序码 如果没有，给他生成一个
        LitemallShop shopss = shopService.getOneByShopID(shop.getId());
        String shareUrl = shopss.getShareUrl();
        if(StringUtils.isEmpty(shareUrl)) {
        	//生成商家小程序码
        	shareUrl = qCodeService.createShopQcode(shop.getId());
        	shop.setShareUrl(shareUrl);
        }
        
        if (shopService.updateById(shop) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        //清除缓存
        deleteObject(null);
        return ResponseUtil.ok(shop);
    }
    
    @RequiresPermissions("admin:shop:updateShopOff")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店管理"}, button = "店铺开关")
    @PostMapping("/updateShopOff")
    public Object updateShopOff(@RequestBody LitemallShop shop) {
    	if(shop.getId() == null) {
    		return ResponseUtil.badArgument();
    	}
    	//先查询店铺是否设置有费率、以及店铺基本的设置
    	//查询 litemall_shop_setting 表 如果根据店铺id查询有数据 说明设置过
    	LitemallShopSetting shopSetting = shopSettingService.getOneByShopId(shop.getId());
    	if(shopSetting == null) {
    		return ResponseUtil.custom("请先设置店铺信息！");
    	}

        if (shopService.updateById(shop) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        //清除缓存
        deleteObject(null);
        redisCache.deleteObject("shop_info_"+shop.getId());

        return ResponseUtil.ok(shop);
    }

    @RequiresPermissions("admin:shop:delete")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallShop shop) {
        Integer id = shop.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        shopService.delShop(shop);
        return ResponseUtil.ok();
    }
    
    @RequiresPermissions("admin:shop:shopIncome")
    @RequiresPermissionsDesc(menu = {"门店管理", "门店收入"}, button = "查询")
    @GetMapping("shopIncome")
    public Object shopIncome(String name, String shopPhone, String shopName,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        return ResponseUtil.okList(shopBalanceService.querySelective(name, shopPhone, shopName, page, limit));
    }
    
    public void deleteObject(Integer shopId) {
        //清除缓存
        redisCache.deleteObject("schoolType_new_1");
        redisCache.deleteObject("schoolType_new_2");
        redisCache.deleteObject("schoolType_new_3");
        //门店缓存
        if(shopId != null) {
        	redisCache.deleteObject("shop_info_"+shopId);
        }
    }
}
